package ez

import (
	"fmt"
	"log"
	"os"
)

// 文件日志
type FileLogger struct {
	Root     string //./var/
	FilePath string //文件名，默认“/orm.log”
	file     *os.File
	Logger   *log.Logger
	MaxSize  int64 //最大容量，默认2M
	MaxLine  int   //最大行数，默认10000
	line     int   //当前行数
	Prefix   string
}

func (this *FileLogger) CreateNewFile() *os.File {
	if this.file != nil {
		e := this.file.Close()
		if e != nil {
			PrintError(e)
		}
	}
	newPath := fmt.Sprintf("%s/orm_%s.log", this.Root, GetDateYMDHIS("", "", "_"))
	info, e := os.Stat(this.FilePath)
	if e != nil {
	} else {
		if info.Size() > this.MaxSize*1024 {
			e := os.Rename(this.FilePath, newPath)
			if e != nil {
				PrintError(e)
			}
		}
	}

	file, e := os.OpenFile(this.FilePath, os.O_CREATE|os.O_APPEND, 0777)
	PrintError(e)
	this.file = file
	return file
}

func NewFileLogger() *FileLogger {
	fl := &FileLogger{
		Root:     "./var/logs",
		FilePath: "./var/logs/orm.log",
		MaxSize:  20 * 1024,
		MaxLine:  100000,
		Prefix:   "[EZ]",
	}
	fl.Logger = log.New(fl.CreateNewFile(), fl.Prefix, log.LstdFlags)

	return fl
}
func (this *FileLogger) Printf(format string, v ...interface{}) {
	this.Logger.Printf(format, v...)
	//文件切换
	needCreateNew := false
	this.line++
	if this.line > this.MaxLine {
		needCreateNew = true
	} else {
		info, e := os.Stat(this.FilePath)
		if e != nil {
			PrintError(e)
			return
		}
		if info.Size() > this.MaxSize*1024 {
			needCreateNew = true
		}
	}
	if needCreateNew {
		this.Logger.SetOutput(this.CreateNewFile())
		this.line = 0
	}
}
